package leetcode.offer_two_special.integer;

/**
 * https://leetcode-cn.com/problems/xoh6Oh/
 *
 * @author mazouri
 * @create 2021-09-04 21:00
 */
public class _01_divide {
    /**
     * @param a 被除数
     * @param b 除数
     * @return 结果
     */
    public int divide(int a, int b) {
        if (a == Integer.MIN_VALUE && b == -1) return Integer.MAX_VALUE;

        int negative = 2;
        if (a > 0) {
            negative--;
            a = -a;
        }

        if (b > 0) {
            negative--;
            b = -b;
        }

        int result = deal(a, b);
        return negative == 1 ? -result : result;


    }

    private int deal(int a, int b) {
        int result = 0;
        while (a <= b) {
            int value = b;
            int quotient = 1;

            while (value >= 0xc0000000 && a <= value + value) {
                quotient += quotient;
                value += value;
            }

            result += quotient;
            a -= value;
        }
        return result;
    }
}
